import { configByID, gameConfig, gameConfigHandle } from 'js/config/gameConfig'
import utils from 'js/core/utils'
import { PartnerModel } from 'js/model/partnerModel'
import { PlayerModel, TitleInfo } from 'js/model/playerModel'
import { BagType, TownBuildType, TownEvent, TownEventType } from 'js/typeDefine/typeDefine'
import bagHandle from './bagHandle'
import partnerHandle from './partnerHandle'
import treasureHandle from './treasureHandle'
import { BagModel } from 'js/model/bagModel'

const resourceText = {
    exp: 'getExp',
    diamond: 'getDiamond',
    gold: 'getGold',
}

class PlayerHandle {
    createPlayer(): PlayerModel {
        let player = new PlayerModel()
        bagHandle.clear(player.bag)
        bagHandle.clear(player.equipmentBag)
        bagHandle.clear(player.treasureBag)
        player.adventureInfo.mapID = gameConfigHandle.gameConfig.base.initMapID
        player.isNewPlayer = true
        return player
    }

    initPlayer(player:PlayerModel, time: number, dTime: number) {
        if (player.baseInfo.dayTime == 0) {
            player.baseInfo.dayTime = dTime
        }
        if (player.baseInfo.weekDayIndex == 0) {
            //1686412800000星期6的24点
            let weekDay = Math.floor((dTime - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
            player.baseInfo.weekDayIndex = weekDay
        }
        this.initBag(player)
        player.teamList.list = player.teamList.list.map(p => {
            if (p) {
                let fighter = partnerHandle.createPartnerFighter(player, p)
                p.fighter = fighter
            }
            return p
        })


        let weekDay = Math.floor((dTime - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        if (player.baseInfo.weekDayIndex != weekDay || player.baseInfo.resetWeekFlag !== true) {
            player.baseInfo.weekDayIndex = weekDay
            player.baseInfo.resetWeekFlag = true
        }
        return player
    }

    initBag(player) {
        let vip = playerHandle.getVipLvl(player)
        let addSize = gameConfigHandle.gameConfig.vip.addBag[vip]
        player.bag.addSize = addSize + player.baseInfo.bagAddSize
        player.bag.type = BagType.Bag
        bagHandle.initPackag(player.bag)
        player.equipmentBag.type = BagType.Equipment
        player.equipmentBag.addSize = addSize + player.baseInfo.eqBagAddSize
        bagHandle.initPackag(player.equipmentBag)
        if (!player.equipmentBag2) {
            player.equipmentBag2 = new BagModel({})
        }
        player.equipmentBag2.type = BagType.Equipment2
        player.equipmentBag2.addSize = addSize + player.baseInfo.eqBag2AddSize
        bagHandle.initPackag(player.equipmentBag2)
        player.treasureBag.type = BagType.Treasure
        player.treasureBag.addSize = addSize + player.baseInfo.trBagAddSize
        bagHandle.initPackag(player.treasureBag)
    }

    initTeam(player: PlayerModel) {
        let active = player.formation.active
        let lvl = player.formation.lvls[active] || 1
        let formationId = gameConfig.baseFormation.list[active]
        let formation = gameConfigHandle.configByID[formationId]
        let attriPos = player.formation.posAttri || {}
        let newAttriPos = {}
        player.teamList.list.forEach((p, i) => {
            if (p && attriPos[p.formationPos]) {
                newAttriPos[p.formationPos] = attriPos[p.formationPos]
            }
        })
        player.formation.posAttri = newAttriPos
        player.teamList.list = player.teamList.list.map((p, i) => {
            if (p) {
                let poss = formation[i]
                let fighter = partnerHandle.createPartnerFighter(player, p)
                fighter.battlePos = poss + 12
                p.fighter = fighter
                if (attriPos[p.formationPos]) {
                    newAttriPos[p.formationPos] = attriPos[p.formationPos]
                }
            }
            return p
        })
    }

    //是否有空闲任务位置
    canStartWbBoss(event: any) {
        if (!event) {
            return false
        }
        return true
    }
    //找到升级需求  达成就扣除需求的资源并返回0   不符合要求返回对应的数字
    getNeedAndUse(player: PlayerModel, needConfig: any, lvl: number, pIndex?: number, coe?: number) {
        //物品消耗
        //遍历
        coe = coe || 100
        let items = needConfig.items
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = Math.floor(utils.getIncValue(items[i].amount, lvl) * coe / 100)
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                if (itemID == 'exp') {
                    let partner = player.teamList.list[pIndex]
                    let myExp = partner.exp
                    if (myExp < amount) {
                        return 1//经验不足
                    }
                }
                else if (itemID == 'gold') {
                    let myGold = player.itemInfo.gold
                    if (myGold < amount) {
                        return 2//金币不足
                    }
                }
                else if (itemID == 'diamond') {
                    let myDiamond = player.itemInfo.diamond
                    if (myDiamond < amount) {
                        return 3//魂晶不足
                    }
                }
                else if (itemID == 'diamond2') {
                    let myDiamond = player.itemInfo.diamond2 || 0
                    if (myDiamond < amount) {
                        return 5//魂晶不足
                    }
                }
                else if (typeof itemID == 'number') {
                    let itemAmount = bagHandle.getTotalNumByItemId(player.bag, itemID)
                    if (itemAmount < amount) {
                        return 4//材料不足
                    }
                }
                else {
                    return 100//配置文件出错
                }
            }
        }
        //资源消耗
        items = needConfig.resourceItems
        let mapConfig = gameConfigHandle.gameConfig.map
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = Math.floor(utils.getIncValue(items[i].amount, lvl) * coe / 100)
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                if (itemID == 'exp') {
                    amount = amount * utils.getIncValue(mapConfig.getExp, lvl)
                    let partner = player.teamList.list[pIndex]
                    if (partner) {
                        let myExp = partner.exp
                        if (myExp < amount) {
                            return 1//经验不足
                        }
                    }
                }
                else if (itemID == 'gold') {
                    let myMoney = player.itemInfo.gold
                    amount = amount * utils.getIncValue(mapConfig.getGold, lvl)
                    if (myMoney < amount) {
                        return 2//金币不足
                    }
                }
                else if (itemID == 'diamond') {
                    let myDiamond = player.itemInfo.diamond
                    amount = amount * utils.getIncValue(mapConfig.getDiamond, lvl)
                    amount = max && amount > max ? max : amount
                    amount = min && amount < min ? min : amount
                    if (myDiamond < amount) {
                        return 3//魂晶不足
                    }
                }
                else if (itemID == 'diamond2') {
                    let myDiamond = player.itemInfo.diamond2 || 0
                    amount = amount * utils.getIncValue(mapConfig.getDiamond2, lvl)
                    amount = max && amount > max ? max : amount
                    amount = min && amount < min ? min : amount
                    if (myDiamond < amount) {
                        return 5//魂晶不足
                    }
                }
                else if (typeof itemID == 'number') {
                    let itemAmount = bagHandle.getTotalNumByItemId(player.bag, itemID)
                    amount = amount * utils.getIncValue(mapConfig.getResource, lvl)
                    if (itemAmount < amount) {
                        return 4//材料不足
                    }
                }
                else {
                    return 100//配置文件出错
                }
            }
        }

        items = needConfig.items
        if (items) {
            //消耗
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let key
                let amount = Math.floor(utils.getIncValue(items[i].amount, lvl) * coe / 100)
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                if (itemID == 'exp') {
                    let partner = player.teamList.list[pIndex]
                    partner.exp -= amount
                    key = 'exp'
                }
                else if (itemID == 'gold') {
                    player.itemInfo.gold -= amount
                    key = 'gold'
                }
                else if (itemID == 'diamond') {
                    player.itemInfo.diamond -= amount
                    key = 'diamond'
                }
                else if (itemID == 'diamond2') {
                    player.itemInfo.diamond2 = (player.itemInfo.diamond2 || 0) - amount
                    key = 'diamond2'
                }
                else if (typeof itemID == 'number') {
                    bagHandle.removeItemByItemId(player.bag, itemID, amount)
                    key = itemID
                }

                if (key) {
                    let useStatAmount = player.itemInfo.usedItemStat[key]
                    if (!useStatAmount) {
                        useStatAmount = 0
                    }
                    player.itemInfo.usedItemStat[key] = useStatAmount + amount
                }
            }
        }


        //资源消耗
        items = needConfig.resourceItems
        if (items) {
            //消耗
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let key
                let amount = Math.floor(utils.getIncValue(items[i].amount, lvl) * coe / 100)
                if (itemID == 'exp') {
                    let partner = player.teamList.list[pIndex]
                    amount = amount * utils.getIncValue(mapConfig.getExp, lvl)
                    let max = items[i].max
                    if (max && amount > max) {
                        amount = max
                    }
                    let min = items[i].min
                    if (min && amount < min) {
                        amount = min
                    }
                    partner.exp -= amount
                    key = 'exp'
                }
                else if (itemID == 'gold') {
                    amount = amount * utils.getIncValue(mapConfig.getGold, lvl)
                    let max = items[i].max
                    if (max && amount > max) {
                        amount = max
                    }
                    let min = items[i].min
                    if (min && amount < min) {
                        amount = min
                    }
                    player.itemInfo.gold -= amount
                    key = 'gold'
                }
                else if (itemID == 'diamond') {
                    amount = amount * utils.getIncValue(mapConfig.getDiamond, lvl)
                    let max = items[i].max
                    if (max && amount > max) {
                        amount = max
                    }
                    let min = items[i].min
                    if (min && amount < min) {
                        amount = min
                    }
                    player.itemInfo.diamond -= amount
                    key = 'diamond'
                }
                else if (typeof itemID == 'number') {
                    amount = amount * utils.getIncValue(mapConfig.getResource, lvl)
                    let max = items[i].max
                    if (max && amount > max) {
                        amount = max
                    }
                    let min = items[i].min
                    if (min && amount < min) {
                        amount = min
                    }
                    bagHandle.removeItemByItemId(player.bag, itemID, amount)
                    key = itemID
                }
                if (key) {
                    let useStatAmount = player.itemInfo.usedItemStat[key]
                    if (!useStatAmount) {
                        useStatAmount = 0
                    }
                    player.itemInfo.usedItemStat[key] = useStatAmount + amount
                }
            }
        }
        return 0
    }

    //返回升级需求  字符串
    getNeedString(needConfig: any, lvl: number) {
        let needList = []
        //物品消耗
        //遍历
        let items = needConfig.items
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = utils.getIncValue(items[i].amount, lvl)

                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                needList.push([itemID, amount])
            }

        }
        //资源消耗
        items = needConfig.resourceItems
        let mapConfig = gameConfigHandle.gameConfig.map
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = utils.getIncValue(items[i].amount, lvl)
                if (typeof itemID == 'number') {
                    amount = amount * utils.getIncValue(mapConfig.getResource, lvl)
                }
                else {
                    amount = amount * utils.getIncValue(mapConfig[resourceText[itemID]], lvl)
                }
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                needList.push([itemID, amount])
            }

        }
        return needList
    }
    //返回升级需求  [itemIDs,itemAmounts]
    getNeed(needConfig: any, lvl: number) {
        let itemIDs = []
        let itemAmounts = []
        //物品消耗
        //遍历
        let items = needConfig.items
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = utils.getIncValue(items[i].amount, lvl)
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                itemIDs.push(itemID)
                itemAmounts.push(amount)
            }

        }
        //资源消耗
        items = needConfig.resourceItems
        let mapConfig = gameConfigHandle.gameConfig.map
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = utils.getIncValue(items[i].amount, lvl)
                if (typeof itemID == 'number') {
                    amount = amount * utils.getIncValue(mapConfig.getResource, lvl)
                }
                else {
                    amount = amount * utils.getIncValue(mapConfig[resourceText[itemID]], lvl)
                }
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                itemIDs.push(itemID)
                itemAmounts.push(amount)
            }

        }
        return [itemIDs, itemAmounts]
    }
    getNeed2(needConfig: any, lvl: number, coe: number = 100) {
        let needItems = []

        //物品消耗
        //遍历
        let items = needConfig.items
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = Math.floor(utils.getIncValue(items[i].amount, lvl) * coe / 100)
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                needItems.push([itemID, amount])
            }

        }
        //资源消耗
        items = needConfig.resourceItems
        let mapConfig = gameConfigHandle.gameConfig.map
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = utils.getIncValue(items[i].amount, lvl)
                if (typeof itemID == 'number') {
                    amount = Math.floor(amount * utils.getIncValue(mapConfig.getResource, lvl) * coe / 100)
                }
                else {
                    amount = Math.floor(amount * utils.getIncValue(mapConfig[resourceText[itemID]], lvl) * coe / 100)
                }
                let max = items[i].max
                if (max && amount > max) {
                    amount = max
                }
                let min = items[i].min
                if (min && amount < min) {
                    amount = min
                }
                needItems.push([itemID, amount])
            }

        }
        return needItems
    }

    //找到武功洗炼需求  达成就扣除需求的资源并返回0   不符合要求返回对应的数字
    getNeedAndUse3(player: PlayerModel, needConfig: any, lvl: number) {
        //物品消耗
        //遍历
        let items = needConfig.items
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = items[i].amount[0] * Math.pow(items[i].amount[1], lvl)
                if (itemID == 'exp') {
                    // if (player.partner.exp < amount) {
                    //     return 1//经验不足
                    // }
                }
                else if (itemID == 'gold') {
                    if (player.itemInfo.gold < amount) {
                        return 2//金币不足
                    }
                }
                else if (itemID == 'diamond') {
                    if (player.itemInfo.diamond < amount) {
                        return 3//魂晶不足
                    }
                }
                else if (itemID == 'skillExp') {
                    if (player.baseInfo.skillExp < amount) {
                        return 4
                    }
                }
                else if (typeof itemID == 'number') {
                    let itemAmount = bagHandle.getTotalNumByItemId(player.bag, itemID)
                    if (itemAmount < amount) {
                        return 4//材料不足
                    }
                }
                else {
                    return 100//配置文件出错
                }
            }
            //消耗
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = items[i].amount[0] * Math.pow(items[i].amount[1], lvl)
                if (itemID == 'exp') {
                    // player.partner.exp -= amount
                }
                else if (itemID == 'gold') {
                    player.itemInfo.gold -= amount
                }
                else if (itemID == 'diamond') {
                    player.itemInfo.diamond -= amount
                }
                else if (itemID == 'skillExp') {
                    player.baseInfo.skillExp -= amount
                }
                else if (typeof itemID == 'number') {
                    bagHandle.removeItemByItemId(player.bag, itemID, amount)
                }
            }
        }
        return 0
    }
    //武功洗炼消耗清单
    getNeed3(needConfig: any, lvl: number) {
        let needItems = []
        let items = needConfig.items
        if (items) {
            for (let i = 0; i < items.length; i++) {
                let itemID = items[i].itemID
                let limitLvl = items[i].limitLvl
                if (limitLvl && (lvl < limitLvl[0] || lvl > limitLvl[1])) {
                    continue
                }
                let amount = items[i].amount[0] * Math.pow(items[i].amount[1], lvl)
                needItems.push([itemID, amount])
            }

        }
        return needItems
    }
    //返回升级所需的某个资源数量
    getNeedAmountOfItem(itemID, lvl, needConfig: any) {
        let needs = this.getNeed(needConfig, lvl)
        let itemIDs = needs[0]
        let itemAmounts = needs[1]
        for (let i = 0; i < itemIDs.length; i++) {
            if (itemID == itemIDs[i]) {
                return itemAmounts[i]
            }
        }
        return 0
    }
    //是否可以升级
    canLvlUp(player: PlayerModel, index) {
        let lvl = player.teamList.list[index].lvl
        let lvlMax = gameConfigHandle.gameConfig.base.levelMax
        if (lvl >= lvlMax) { return false }
        let needExp = this.getLvlUpExp(player, index)
        let exp = player.teamList.list[index].exp
        if (needExp > exp) {
            return false
        } else {
            return true
        }
    }
    //角色升级所需经验
    getLvlUpExp(player: PlayerModel, index, flag: boolean = false) {
        let lvl = flag ? player.teamList.camp[index].lvl : player.teamList.list[index].lvl
        let lvlMax = gameConfigHandle.gameConfig.base.levelMax
        if (lvl >= lvlMax) { return 0 }
        let partnerConfig = gameConfigHandle.gameConfig.partner
        let needItems = partnerConfig.LvlupAttriNeed.resourceItems
        let amount
        for (let i = 0; i < needItems.length; i++) {
            if (needItems[i].itemID == 'exp') {
                amount = needItems[i].amount
            }
        }
        if (!amount) { return 0 }
        let mapConfig = gameConfigHandle.gameConfig.map
        let up = 1
        if (mapConfig.getExp) { up = utils.getIncValue(mapConfig.getExp, lvl - 1) }
        let exp = utils.getIncValue(amount, lvl) * up

        //倍增效果
        let beizengStartLvl = gameConfigHandle.gameConfig.partner.beizengStartLvl
        let beizengValue = gameConfigHandle.gameConfig.partner.beizengValue
        if (lvl <= 200) {
            if (lvl >= beizengStartLvl) {
                let bzLvl = Math.floor((lvl - beizengStartLvl) / 10) + 1
                let value = utils.getIncValue(beizengValue, bzLvl)
                exp *= value
            }
        } else {
            let baseLvl = 200
            let bzLvl = Math.floor((lvl - beizengStartLvl) / 10) + 1
            let value = utils.getIncValue(beizengValue, bzLvl)
            exp *= value
            // 超级倍增
            let overLvl = lvl - baseLvl
            beizengValue = gameConfig.partner.superBeizengValue
            bzLvl = Math.floor(overLvl / 10) + 1
            value = utils.getIncValue(beizengValue, bzLvl)
            exp *= value
        }
        return exp
    }

    //角色升级所需经验
    getLvlUpExpByCamp(player: PlayerModel, index) {
        let lvl = player.teamList.camp[index].lvl
        let lvlMax = gameConfigHandle.gameConfig.base.levelMax
        if (lvl >= lvlMax) { return 0 }
        let partnerConfig = gameConfigHandle.gameConfig.partner
        let needItems = partnerConfig.LvlupAttriNeed.resourceItems
        let amount
        for (let i = 0; i < needItems.length; i++) {
            if (needItems[i].itemID == 'exp') {
                amount = needItems[i].amount
            }
        }
        if (!amount) { return 0 }
        let mapConfig = gameConfigHandle.gameConfig.map
        let up = 1
        if (mapConfig.getExp) { up = utils.getIncValue(mapConfig.getExp, lvl - 1) }
        let exp = utils.getIncValue(amount, lvl) * up

        //倍增效果
        let beizengStartLvl = gameConfigHandle.gameConfig.partner.beizengStartLvl
        let beizengValue = gameConfigHandle.gameConfig.partner.beizengValue
        if (lvl >= beizengStartLvl) {
            let bzLvl = Math.floor((lvl - beizengStartLvl) / 10) + 1
            let value = utils.getIncValue(beizengValue, bzLvl)
            exp *= value
        }
        return exp
    }
    //角色升级所需经验
    getLvlUpExp1(lvl: number) {
        let lvlMax = gameConfigHandle.gameConfig.base.levelMax
        if (lvl >= lvlMax) { return 0 }
        let partnerConfig = gameConfigHandle.gameConfig.partner
        let needItems = partnerConfig.LvlupAttriNeed.resourceItems
        let amount
        for (let i = 0; i < needItems.length; i++) {
            if (needItems[i].itemID == 'exp') {
                amount = needItems[i].amount
            }
        }
        if (!amount) { return 0 }
        let mapConfig = gameConfigHandle.gameConfig.map
        let up = 1
        if (mapConfig.getExp) { up = utils.getIncValue(mapConfig.getExp, lvl - 1) }
        let exp = utils.getIncValue(amount, lvl) * up

        //倍增效果
        let beizengStartLvl = gameConfigHandle.gameConfig.partner.beizengStartLvl
        let beizengValue = gameConfigHandle.gameConfig.partner.beizengValue
        if (lvl >= beizengStartLvl) {
            let bzLvl = Math.floor((lvl - beizengStartLvl) / 10) + 1
            let value = utils.getIncValue(beizengValue, bzLvl)
            exp *= value
        }
        return exp
    }
    //返回对应属性强化等级的属性值
    getAtrriNumOfAtrriStr(attriName: string, atrriStrLvl: number, attriConfig) {
        let AtrriStrNames = gameConfigHandle.gameConfig.partner.attris
        let amount = attriConfig[attriName]
        let attriNum = utils.getIncValue(amount, atrriStrLvl)
        return attriNum
    }

    //返回经脉属性值
    getAtrriNumOfJingmai(index: number, jingmaiLvl: number, attriConfig) {
        let AtrriNames = gameConfigHandle.gameConfig.partner.jingmaiAttris
        let values = attriConfig[AtrriNames[index]]
        let total = 0
        let strLvl = Math.floor(jingmaiLvl / 10) + 1;
        for (let i = 0; i < strLvl; i++) {
            let value = values[1] + values[2] * i
            if (i == strLvl - 1) {
                total += value * (jingmaiLvl % 10)
            } else {
                total += value * 10
            }
        }
        return total
    }

    //获取经脉阶级等级和提升 百分比提升属性
    getJingMaiJjUp(index, jmLvl) {
        let jjLvl = Math.floor(jmLvl / 10)
        let jingMaiJjUpPerConfig = gameConfigHandle.gameConfig.partner.jingMaiJjUpPer
        let attriPersConfig = gameConfigHandle.gameConfig.partner.attriPers
        let configAmount = jingMaiJjUpPerConfig[attriPersConfig[index]]
        let jingMaiJjUp = utils.getIncValue(configAmount, jjLvl, true)
        return [jjLvl, jingMaiJjUp]
    }

    //获得可上阵武功最大数量
    getSkillBookOnAmountMax(partner: PartnerModel, player: PlayerModel) {
        let pLvl = partner.lvl
        let skillBookAmount = gameConfigHandle.gameConfig.partner.skillBookAmount
        let max = 0
        skillBookAmount.forEach((learnLvl, i) => {
            if (pLvl > learnLvl) {
                max = i + 1
            }
        })
        return max
    }

    resetDay(player: PlayerModel, random) {
        player.baseInfo.signIn = 1
        player.baseInfo.signIn2 = 1
        player.baseInfo.mainTip = false
        player.baseInfo.sweepTip = false
        player.market.refreshTimes = 0
        // player.barTeamList = new Array(5).fill(null)
        player.deepInfo.times = 0
        player.deepInfo.nightTimes = 0
        player.deepInfo.nightTodayProgress = 0
        player.baseInfo.refreshBarTimes = 0
        player.wbInfo.todayTimes = 0
        player.task.refreshTimes = 0
        player.alchemyInfo.accelerateTimes = 0
        if (!player.floorStop) {
            player.floorStop = {}
        }
        player.floorStop.triggerTimes = 0
        player.townInfo.signInInfo = { selfSignIn: false, serverSignIn: false }
        player.townInfo.searchTaskList = []
        player.townInfo.dayTownTaskTimes = 0
        player.townInfo.searchTimes = 0
        player.market.townMarketItems = []
        this.resetTownMarketItems(player, random)
    }
    resetTownMarketItems(player: PlayerModel, random) {
        let marketItems = []
        let townMarketItems = utils.getRandomArrayNoRepeat(gameConfig.town.townMarketItems, gameConfig.town.townMarketDayItemNum, random)
        for (let i = 0; i < townMarketItems.length; i++) {
            let item = Object.assign({}, townMarketItems[i])
            item['buyTimes'] = 0
            marketItems.push(item)
        }
        player.market.townMarketItems = marketItems
    }
    resetTownTask(player: PlayerModel, random) {
        let randomTask = utils.getRandomArrayNoRepeat(gameConfig.town.task, 3, random)
        let taskList = []
        for (let i = 0; i < randomTask.length; i++) {
            let task = {}
            let taskConfig = randomTask[i];
            task['kind'] = taskConfig.kind
            task['name'] = taskConfig.name
            let randomNum = random.intn(100)
            let result = randomNum > taskConfig.failRate
            task['result'] = result
            task['desc'] = taskConfig.desc
            task['status'] = 0
            task['resultDesc'] = result ? taskConfig.successDesc : taskConfig.failDesc
            task['saveScore'] = taskConfig.values2[0] + random.intn(taskConfig.values2[1])
            task['timeConfig'] = taskConfig.values
            let rewardConfig = taskConfig.reward
            if (rewardConfig.random) {
                let get = rewardConfig.items[random.intn(rewardConfig.items.length - 1)]
                if (get.itemID == 'treasure') {
                    let quailityCoe = player.townInfo.lvl % 2
                    let quality = random.intn(quailityCoe)
                    let tid = utils.getOneFromArray(taskConfig.dropItems, random)
                    let item = treasureHandle.createTreasure(tid, 1, random, quality)
                    task['reward'] = { itemID: 'treasure', value: item }
                    taskList.push(task)
                } else {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    if (get.itemID == 170031) {
                        task['values1'] = getResource
                    }
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    taskList.push(task)
                }
            } else {
                let get = rewardConfig.resourceItems[0]
                if (get.itemID == 'gold') {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    getResource = Math.floor(getResource * utils.getIncValue(gameConfig.map.getGold, player.townInfo.lvl))
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    taskList.push(task)
                } else if (get.itemID == 'diamond') {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    getResource = Math.floor(getResource * utils.getIncValue(gameConfig.map.getDiamond, player.townInfo.lvl))
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    taskList.push(task)
                } else {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    let itemConfig = gameConfigHandle.configByID[get.itemID]
                    let resourceCoe = itemConfig.lvl > 10 ? 0.3 : 1
                    getResource = Math.floor(getResource * utils.getIncValue(gameConfig.map.getResource, player.townInfo.lvl) * resourceCoe)
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    taskList.push(task)
                }

            }
        }
        player.townInfo.taskList = taskList
    }

    resetTownTask2(player: PlayerModel, random) {
        let count = 3, oTaskList = []
        player.townInfo.taskList.forEach(t => {
            oTaskList.push(t)
            if (t.status == 1 || t.status == 0) {
                count -= 1
            }
        });
        let randomTask = []
        if (count == 3 && (player.townInfo.dayTownTaskTimes || 0) < 3) {
            oTaskList = []
            player.townInfo.dayTownTaskTimes = (player.townInfo.dayTownTaskTimes || 0) + 1
            randomTask = utils.getRandomArrayNoRepeat(gameConfig.town.task, 3, random)
        }
        for (let i = 0; i < randomTask.length; i++) {
            let task = {}
            let taskConfig = randomTask[i];
            task['kind'] = taskConfig.kind
            task['name'] = taskConfig.name
            let randomNum = random.intn(100)
            let result = randomNum > taskConfig.failRate
            task['result'] = result
            task['desc'] = taskConfig.desc
            task['status'] = 0
            task['resultDesc'] = result ? taskConfig.successDesc : taskConfig.failDesc
            task['saveScore'] = taskConfig.values2[0] + random.intn(taskConfig.values2[1])
            task['timeConfig'] = taskConfig.values
            let rewardConfig = taskConfig.reward
            if (rewardConfig.random) {
                let get = rewardConfig.items[random.intn(rewardConfig.items.length - 1)]
                if (get.itemID == 'treasure') {
                    let quailityCoe = player.townInfo.lvl % 2
                    let quality = random.intn(quailityCoe)
                    let tid: any = utils.getOneFromArray(taskConfig.dropItems, random)
                    let item = treasureHandle.createTreasure(tid, 1, random, quality)
                    task['reward'] = { itemID: 'treasure', value: item }
                    oTaskList.push(task)
                } else {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    if (get.itemID == 170031) {
                        task['values1'] = getResource
                    }
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    oTaskList.push(task)
                }
            } else {
                let get = rewardConfig.resourceItems[0]
                if (get.itemID == 'gold') {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    getResource = Math.floor(getResource * utils.getIncValue(gameConfig.map.getGold, player.townInfo.lvl))
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    oTaskList.push(task)
                } else if (get.itemID == 'diamond') {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    getResource = Math.floor(getResource * utils.getIncValue(gameConfig.map.getDiamond, player.townInfo.lvl))
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    oTaskList.push(task)
                } else {
                    let getResource = utils.getIncValue(get.amount, player.townInfo.lvl)
                    let itemConfig = gameConfigHandle.configByID[get.itemID]
                    let resourceCoe = itemConfig.lvl > 10 ? 0.3 : 1
                    getResource = Math.floor(getResource * utils.getIncValue(gameConfig.map.getResource, player.townInfo.lvl) * resourceCoe)
                    task['reward'] = { itemID: get.itemID, value: getResource }
                    oTaskList.push(task)
                }

            }
        }
        player.townInfo.taskList = oTaskList
    }

    createTownSearchTask(player: PlayerModel, isUseItem, time, random) {
        let searchTaskList = player.townInfo.searchTaskList
        if (searchTaskList.length > gameConfig.town.eventMaxTimes) {
            return []
        }
        if (player.baseInfo.longVip && searchTaskList.length >= gameConfig.town.eventMaxTimes) {
            return []
        } else if (!player.baseInfo.longVip) {
            let addOfAfd = gameConfig.vip.townSearchAddOfAfd
            if (this.isMember(player, time) && searchTaskList.length >= gameConfig.town.eventFreeTimes + addOfAfd) {
                return []
            } else if (!this.isMember(player, time) && searchTaskList.length >= gameConfig.town.eventFreeTimes) {
                return []
            }
        }
        let rate = isUseItem ? 20 : 1
        let triggerRareTask = random.intn(100) <= rate
        let events = []
        let playerTriggerTreasure = (player.townInfo.searchTaskTriggerTimes || 0)
        if (triggerRareTask) {
            events = gameConfig.town.events.filter(e => e.triggerRate)
            let otherEvents = gameConfig.town.events.filter(e => {
                if (e.triggerRate && playerTriggerTreasure < 2) {
                    return true
                } else if (e.triggerRate && playerTriggerTreasure >= 2) {
                    return e.kind != TownEvent.CheatRewardBadge
                        && e.kind != TownEvent.Deep
                        && e.kind != TownEvent.Build
                        && e.kind != TownEvent.ChestRewardTreasure
                }
                return false
            })
            if (otherEvents.length == 0) {
                let rareEvent = utils.getOneFromArray(gameConfig.town.events.filter(e => e.triggerRate), random)
                otherEvents = gameConfig.town.events.filter(e => !e.triggerRate)
                otherEvents.push(rareEvent)
                otherEvents = gameConfig.town.events
            }
            utils.getRandomArrayNoRepeat(otherEvents, 1, random).forEach(e => {
                events.push(e)
            })
            player.townInfo.searchTaskTriggerTimes = playerTriggerTreasure + 1
        } else {
            let rareEvent = utils.getOneFromArray(gameConfig.town.events.filter(e => e.triggerRate && e.kind != TownEvent.ChestRewardTreasure && e.kind != TownEvent.Build), random)
            events = gameConfig.town.events.filter(e => !e.triggerRate)
            events.push(rareEvent)
        }
        let eventList = utils.getRandomArrayNoRepeat(events, 1, random)
        return eventList
    }

    getVipExp(player: PlayerModel) {
        return Math.floor(player.baseInfo.vipExp)
    }

    getVipLvl(player: PlayerModel) {
        let exp = Math.floor(player.baseInfo.vipExp)
        let vipConfig = gameConfigHandle.gameConfig.vip
        let vip = 0
        for (let i = 0; i < vipConfig.vipLvlUpNeed.length; i++) {
            let needVip = vipConfig.vipLvlUpNeed[i]
            if (exp >= needVip) {
                vip = i
            }
        }
        //等级上限
        let vipLvlMax = gameConfigHandle.gameConfig.vip.vipLvlMax
        if (vip > vipLvlMax) {
            vip = vipLvlMax
        }
        return vip
    }
    isMember(player: PlayerModel, time: number) {
        if (player.baseInfo.vipTime >= time) {
            return true
        } else {
            return false
        }
    }

    getEmptyPos(player: PlayerModel) {
        let emptyIndex = null
        for (let i = 0; i < 12; i++) {
            if (!player.teamList.list.find(f => f && f.formationPos == i)) {
                emptyIndex = i
            }
        }
        return emptyIndex
    }

    setTeamPos(player: PlayerModel, pos, index) {
        player.teamList.pos[pos] = index
        return true
    }

    getWbMapId(player: PlayerModel, time, random) {
        let mapId = gameConfig.map.wbBaseMapId
        // 版本测试 rate = 5
        let rate = 20
        // if (userData.test) {
        //     rate = 70
        // }
        if (this.isMember(player, time)) {
            rate += gameConfig.vip.addNewWbRateOfAfd || 0
        }
        let vip = this.getVipLvl(player)
        if (vip) {
            rate += gameConfig.vip.addNewWbRate[vip] || 0
        }
        let randomRate = random.intn(100)
        if (randomRate < rate) {
            mapId = gameConfig.map.wbNewMapId
        }
        return mapId
    }

    floorStopCoe(player: PlayerModel, mapID, floor) {
        let coe = 100
        if (mapID < gameConfig.map.floorStopMinMap || !player.floorStop.mapID || player.floorStop.triggerTimes >= gameConfig.map.triggerTimesLimit) {
            return coe
        }
        if (player.floorStop.mapID == mapID && player.floorStop.floor == floor && player.floorStop.stopTimes >= gameConfig.map.floorStopTrigger) {
            let entries = Object.entries(gameConfig.map.floorStop)
            entries.forEach(entry => {
                let times = entry[0]
                if (player.floorStop.stopTimes >= times) {
                    coe = entry[1]
                }
            })
        }
        return coe
    }

    isPowerSet(player) {
        return player.baseInfo.animationType == 3
    }

    getPlayerTitles(id: number, time, player: PlayerModel) {
        const attriList = ['maxHp', "attack", 'def', "hit", "dodge", "crit", 'critHurt', "attackSpeed", "recoverHp"]
        const equipPart = ['hand', 'head', 'subHand', 'body', 'palm', 'foot']
        if (id) {
            let infos = player.titleInfo.infos || {}
            let active = infos[id] != null
            let config = gameConfigHandle.configByID[id]
            if (config && !active) {
                let condition = config.condition
                active = true
                condition.forEach((c, i) => {
                    if (c.conditionType == 'longVip' && active) {
                        active = player.baseInfo.longVip
                    } else if (c.conditionType == 'SSSPartner' && active) {
                        let allSSS = 10
                        for (let i = 0; i < 10; i++) {
                            try {
                                let partner = player.teamList.list[i];
                                if (!partner || partner.quality != 5) {
                                    break
                                }
                                let oSSS = false
                                attriList.forEach(a => {
                                    let attriName = a
                                    let score = partnerHandle.attriScore(attriName, partner.fighter.tID, partner.customFeature) || 'C'
                                    if (score == 'SSS') {
                                        oSSS = true
                                    }
                                })
                                if (oSSS) {
                                    allSSS -= 1
                                }
                            } catch (error) {
                                break
                            }
                        }
                        active = allSSS == 0
                    } else if (c.conditionType == 'SPartner' && active) {
                        let allS = 10
                        for (let i = 0; i < 10; i++) {
                            try {
                                let partner = player.teamList.list[i];
                                if (!partner || partner.quality != 5) {
                                    break
                                }
                                allS -= 1
                            } catch (error) {
                                break
                            }
                        }
                        active = allS == 0
                    } else if (c.conditionType == 'wbDamage' && active) {
                        active = player.wbInfo.progress >= c.value
                    } else if (c.conditionType == 'deepCount' && active) {
                        active = player.deepInfo.progress >= c.value
                    } else if (c.conditionType == 'nightCount' && active) {
                        active = player.deepInfo.nightProgress >= c.value
                    } else if (c.conditionType == 'townLvl' && active) {
                        active = player.townInfo.lvl >= c.value
                    } else if (c.conditionType == 'townTaskLvl' && active) {
                        active = player.townInfo.subBuildLvl[TownBuildType.Task] >= c.value
                    } else if (c.conditionType == 'townMakeLvl' && active) {
                        active = player.townInfo.subBuildLvl[TownBuildType.Make] >= c.value
                    } else if (c.conditionType == 'townBooming' && active) {
                        active = player.townInfo.booming >= c.value
                    } else if (c.conditionType == 'barRecuritTimes' && active) {
                        active = (player.baseInfo.barRecuritTimes1 || 0) >= c.value
                    } else if (c.conditionType == 'gem' && active) {
                        let allGemActive = 240
                        for (let i = 0; i < 10; i++) {
                            if (!allGemActive) {
                                break
                            }
                            try {
                                let partner = player.teamList.list[i];
                                if (!partner) {
                                    break
                                }
                                let equipments = partner.equipments[0]
                                for (let j = 0; j < equipPart.length; j++) {
                                    let ep = equipPart[j]
                                    let equip = equipments[ep];
                                    if (!equip && allGemActive) {
                                        break
                                    } else if ((!equip.equipment.gems || equip.equipment.gems.length < 4) && allGemActive) {
                                        break
                                    } else if (allGemActive) {
                                        let gems = equip.equipment.gems
                                        if (gems.length == 4) {
                                            for (let j = 0; j < gems.length; j++) {
                                                let gem = gems[j]
                                                if ((!gem || gem.hp < c.value)) {
                                                    break
                                                } else if (gem.hp >= c.value) {
                                                    allGemActive -= 1
                                                }
                                            }
                                        } else {
                                            break
                                        }
                                    }
                                }
                            } catch (error) {
                                break
                            }
                        }
                        active = allGemActive == 0
                    }
                })
                if (!player.titleInfo || !player.titleInfo.infos) {
                    player.titleInfo = new TitleInfo({})
                }
                if (active && !player.titleInfo.infos[id]) {
                    player.titleInfo.infos[id] = time
                    return true
                }
                return false
            }
            return false
        } else {
            let titles = gameConfig.titles
            Object.entries(titles).forEach(t => {
                let id = t[0]
                let infos = player.titleInfo?.infos || {}
                let active = infos[id] != null
                let config = gameConfigHandle.configByID[id]
                if (config && !active) {
                    let condition = config.condition
                    active = true
                    condition.forEach((c, i) => {
                        if (c.conditionType == 'longVip' && active) {
                            active = player.baseInfo.longVip
                        } else if (c.conditionType == 'SSSPartner' && active) {
                            let allSSS = 10
                            for (let i = 0; i < 10; i++) {
                                try {
                                    let partner = player.teamList.list[i];
                                    if (!partner || partner.quality != 5) {
                                        break
                                    }
                                    let oSSS = false
                                    attriList.forEach(a => {
                                        let attriName = a
                                        let score = partnerHandle.attriScore(attriName, partner.fighter.tID, partner.customFeature) || 'C'
                                        if (score == 'SSS') {
                                            oSSS = true
                                        }
                                    })
                                    if (oSSS) {
                                        allSSS -= 1
                                    }
                                } catch (error) {
                                    break
                                }
                            }
                            active = allSSS == 0
                        } else if (c.conditionType == 'SPartner' && active) {
                            let allS = 10
                            for (let i = 0; i < 10; i++) {
                                try {
                                    let partner = player.teamList.list[i];
                                    if (!partner || partner.quality != 5) {
                                        break
                                    }
                                    allS -= 1
                                } catch (error) {
                                    break
                                }
                            }
                            active = allS == 0
                        } else if (c.conditionType == 'wbDamage' && active) {
                            active = player.wbInfo.progress >= c.value
                        } else if (c.conditionType == 'deepCount' && active) {
                            active = player.deepInfo.progress >= c.value
                        } else if (c.conditionType == 'nightCount' && active) {
                            active = player.deepInfo.nightProgress >= c.value
                        } else if (c.conditionType == 'townLvl' && active) {
                            active = player.townInfo.lvl >= c.value
                        } else if (c.conditionType == 'townTaskLvl' && active) {
                            active = player.townInfo.subBuildLvl[TownBuildType.Task] >= c.value
                        } else if (c.conditionType == 'townMakeLvl' && active) {
                            active = player.townInfo.subBuildLvl[TownBuildType.Make] >= c.value
                        } else if (c.conditionType == 'townBooming' && active) {
                            active = player.townInfo.booming >= c.value
                        } else if (c.conditionType == 'barRecuritTimes' && active) {
                            active = (player.baseInfo.barRecuritTimes1 || 0) >= c.value
                        } else if (c.conditionType == 'gem' && active) {
                            let allGemActive = 240
                            for (let i = 0; i < 10; i++) {
                                if (!allGemActive) {
                                    break
                                }
                                try {
                                    let partner = player.teamList.list[i];
                                    if (!partner) {
                                        break
                                    }
                                    let equipments = partner.equipments[0]
                                    for (let j = 0; j < equipPart.length; j++) {
                                        let ep = equipPart[j]
                                        let equip = equipments[ep];
                                        if (!equip && allGemActive) {
                                            break
                                        } else if ((!equip.equipment.gems || equip.equipment.gems.length < 4) && allGemActive) {
                                            break
                                        } else if (allGemActive) {
                                            let gems = equip.equipment.gems
                                            if (gems.length == 4) {
                                                for (let j = 0; j < gems.length; j++) {
                                                    let gem = gems[j]
                                                    if ((!gem || gem.hp < c.value)) {
                                                        break
                                                    } else if (gem.hp >= c.value) {
                                                        allGemActive -= 1
                                                    }
                                                }
                                            } else {
                                                break
                                            }
                                        }
                                    }
                                } catch (error) {
                                    break
                                }
                            }
                            active = allGemActive == 0
                        }
                    })
                    if (!player.titleInfo || !player.titleInfo.infos) {
                        player.titleInfo = new TitleInfo({})
                    }
                    if (active && !player.titleInfo.infos[id]) {
                        player.titleInfo.infos[id] = time
                    }
                }
            })
            return false
        }
    }
}

let playerHandle = new PlayerHandle()
export default playerHandle

